package com.goldplusgold.tradedelay.app.home.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.goldplusgold.imageloader.lib.GlideRoundTransform;
import com.goldplusgold.live.LVDataManager;
import com.goldplusgold.live.bean.LiveBean;
import com.goldplusgold.live.bean.VideoBean;
import com.goldplusgold.live.result.ResultLives;
import com.goldplusgold.live.result.ResultVideos;
import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.tradedelay.app.home.live.base.BaseCallback;
import com.goldplusgold.support.lib.base.fragment.BaseNetWorkFragment;
import com.goldplusgold.support.lib.utils.Logger;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.support.lib.widget.pulltorefresh.PullToRefreshBase;
import com.goldplusgold.support.lib.widget.pulltorefresh.PullToRefreshScrollView;
import com.goldplusgold.support.lib.widget.scroller.ListViewInScrollView;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.home.live.PullListActivity;
import com.goldplusgold.tradedelay.app.home.live.LiveDetailActivity;
import com.goldplusgold.tradedelay.app.home.live.base.LiveBaseCallBack;
import com.goldplusgold.tradedelay.app.main.activity.TDMainActivity;
import com.goldplusgold.support.lib.hybird.WebViewActivity;
import com.goldplusgold.tradedelay.app.home.activity.ExpertArticleActivity;
import com.goldplusgold.tradedelay.app.home.adapter.ArticleAdapter;
import com.goldplusgold.tradedelay.app.home.serivce.ApiConfig;
import com.goldplusgold.tradedelay.app.home.serivce.HomeService;
import com.goldplusgold.tradedelay.app.home.pojo.Article;
import com.goldplusgold.tradedelay.app.home.pojo.ArticleList;
import com.goldplusgold.tradedelay.app.home.pojo.Banner;
import com.goldplusgold.tradedelay.app.home.pojo.BannerList;
import com.goldplusgold.tradedelay.app.market.eventbus.DynaMessageEvent;
import com.goldplusgold.tradedelay.app.market.eventbus.SltpNotificationMessageEvent;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.my.account.UserInfo;
import com.goldplusgold.network.lib.http.netty.ChannelManager;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.tradedelay.app.trade.dialog.DeleteWarmTipDialog;
import com.goldplusgold.tradedelay.app.trade.dialog.WarmTipDialog;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.utils.StringConvertNumber;
import com.goldplusgold.tradedelay.app.base.widget.ViewFactory;
import com.goldplusgold.tradedelay.app.base.widget.lib.CycleViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;


/**
 * Created by admin on 2017/5/8.
 */
public class HomeFragment extends BaseNetWorkFragment implements Handler.Callback, PullToRefreshScrollView.OnRefreshListener {

    @BindView(R.id.id_scroll_view_layout)
    PullToRefreshScrollView mScrollView;
    CycleViewPager mBannerViewPager;
    @BindView(R.id.au_price)
    TextView mAUPrice;
    @BindView(R.id.au_rise)
    TextView mAURise;
    @BindView(R.id.ag_price)
    TextView mAGPrice;
    @BindView(R.id.ag_rise)
    TextView mAGRose;
    @BindView(R.id.mau_price)
    TextView mMAUPrice;
    @BindView(R.id.mau_rise)
    TextView mMAURise;
    @BindView((R.id.id_list_view_news))
    ListViewInScrollView mArticleList;
    @BindView(R.id.id_text_view_economic_calendar)
    TextView idTextViewEconomicCalendar;
    @BindView(R.id.id_text_view_guide)
    TextView idTextViewGuide;
    @BindView(R.id.id_text_view_quick_account)
    TextView idTextViewQuickAccount;
    @BindView(R.id.id_text_view_more)
    TextView mTextViewMore;

    @BindView(R.id.id_text_view_live_more)
    TextView tv_live_more;

    @BindView(R.id.id_text_view_video_more)
    TextView tv_video_more;
    @BindView(R.id.layout_live_container_oitem_img_control)
    ImageView layout_live_container_oitem_img_control;
    @BindView(R.id.layout_live_container_oitem_txt_state)
    TextView layout_live_container_oitem_txt_state;
    @BindView(R.id.layout_live_container_titem_img_control)
    ImageView layout_live_container_titem_img_control;
    @BindView(R.id.layout_live_container_titem_txt_state)
    TextView layout_live_container_titem_txt_state;
    @BindView(R.id.layout_live_container_oitem_img_state)
    ImageView layout_live_container_oitem_img_state;
    @BindView(R.id.layout_live_container_titem_img_state)
    ImageView layout_live_container_titem_img_state;
    @BindView(R.id.layout_live_container_oitem_txt_state_img)
    TextView layout_live_container_oitem_txt_state_img;
    @BindView(R.id.layout_live_oitem)
    RelativeLayout layout_live_oitem;
    @BindView(R.id.layout_live_titem)
    RelativeLayout layout_live_titem;
    @BindView(R.id.layout_live_container_titem_txt_state_img)
    TextView layout_live_container_titem_txt_state_img;
    @BindView(R.id.layout_video_container_oitem_img_back)
    RelativeLayout layout_video_container_oitem_img_back;
    @BindView(R.id.layout_video_container_oitem_img_control)
    ImageView layout_video_container_oitem_img_control;
    @BindView(R.id.layout_video_container_oitem_txt_title)
    TextView layout_video_container_oitem_txt_title;

    @BindView(R.id.layout_video_container_titem_img_back)
   RelativeLayout layout_video_container_titem_img_back;
    @BindView(R.id.layout_video_container_titem_img_control)
    ImageView layout_video_container_titem_img_control;
    @BindView(R.id.layout_video_container_titem_txt_title)
    TextView layout_video_container_titem_txt_title;

    @BindView(R.id.layout_live_oitem_iv)
    ImageView layout_live_oitem_iv;
    @BindView(R.id.layout_live_titem_iv)
    ImageView layout_live_titem_iv;
    @BindView(R.id.layout_video_container_oitem_img)
    ImageView layout_video_container_oitem_img;
    @BindView(R.id.layout_video_container_titem_img)
    ImageView layout_video_container_titem_img;

    ResultVideos videos;
    ResultLives  lives;

    private Handler  handler = new Handler(this);
    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(Banner info, View imageView) {
            if (mBannerViewPager.isCycle()) {
                String url = info.getLinkUrl();
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
            }
        }

    };
    private ArticleAdapter mArticleListAdapter;

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }


    @Override
    public void initView() {
        this.mBannerViewPager = ((CycleViewPager) getChildFragmentManager().findFragmentById(R.id.fragment_cycle_viewpager_content));
        mArticleListAdapter = new ArticleAdapter(getActivity());
        mArticleList.setAdapter(mArticleListAdapter);
        mArticleList.setOnItemClickListener(mArticleListAdapter);
        mArticleList.setFocusable(false);
        mScrollView.setOnRefreshListener(this);
        new LoadBannerAsyncTask().execute(AsyncTask.TYPE_NET);
        requestMarket();
        new LoadArticleAsyncTask().execute(AsyncTask.TYPE_NET);
        requestLiveAndVideoData();


    }

    private void refreshVideoItem(ResultVideos body) {
        if(body != null){
            videos = body;
            if(body.getVideos() != null && body.getVideos().size() != 0){
                List<VideoBean> videos = body.getVideos();
                if(videos.size() == 1){
                    Glide.with(getActivity()).load(videos.get(0).getBackgroundImg())
                            .asBitmap().error(R.drawable.live)
                            .transform(new CenterCrop(getActivity()) , new GlideRoundTransform(getActivity(),4))
                            .into(layout_video_container_oitem_img);

                    layout_video_container_oitem_txt_title.setText(videos.get(0).getVideoTitle());
                } else if(videos.size() >= 2){
                    Glide.with(getActivity()).load(videos.get(0).getBackgroundImg())
                            .asBitmap().error(R.drawable.live)
                            .transform(new CenterCrop(getActivity()) , new GlideRoundTransform(getActivity(),4))
                            .into(layout_video_container_oitem_img);
                    Glide.with(getActivity()).load(videos.get(1).getBackgroundImg())
                            .asBitmap().error(R.drawable.live)
                            .transform(new CenterCrop(getActivity()) , new GlideRoundTransform(getActivity(),4))
                            .into(layout_video_container_titem_img);
                    layout_video_container_oitem_txt_title.setText(videos.get(0).getVideoTitle());
                    layout_video_container_titem_txt_title.setText(videos.get(1).getVideoTitle());
                }
            }
        }
    }

    //TODO 带有优化一下, 去掉ISHOW by hur
    private void refreshLiveItem(ResultLives body) {
        if(body != null){
            lives = body;
            if(body.getLives() != null && body.getLives().size() != 0){
                List<LiveBean> lives = body.getLives();
                if(lives.size() >=2){
                    Glide.with(this)
                            .load(lives.get(0).getColumnIcon())
                            .asBitmap()
                            .error(R.drawable.live)
                            .transform(new CenterCrop(getActivity()) , new GlideRoundTransform(getActivity() , 4))
                            .into(layout_live_oitem_iv);

                    Glide.with(this)
                            .load(lives.get(1).getColumnIcon())
                            .asBitmap()
                            .error(R.drawable.live)
                            .transform(new CenterCrop(getActivity()) , new GlideRoundTransform(getActivity(),4))
                            .into(layout_live_titem_iv);

                    if(lives.get(0).getLiveType() == 0){
                        layout_live_container_oitem_img_state.setBackgroundResource(R.drawable.home_icon_word);
                    } else{
                        layout_live_container_oitem_img_state.setBackgroundResource(R.drawable.home_icon_video);
                    }
                    if(lives.get(1).getLiveType() == 0){
                        layout_live_container_titem_img_state.setBackgroundResource(R.drawable.home_icon_word);
                    } else{
                        layout_live_container_titem_img_state.setBackgroundResource(R.drawable.home_icon_video);
                    }

                    if(lives.get(0).getLiveStatus() == 0 ||lives.get(0).getLiveStatus()== 20){
                        layout_live_container_oitem_txt_state_img.setVisibility(View.GONE);
                        //String [] time = lives.get(0).getLiveTime().split(" ")[1].split(":");
                        //layout_live_container_oitem_txt_state_img.setBackgroundResource(R.drawable.home_icon_rest);
                        layout_live_container_oitem_txt_state.setText(lives.get(0).getLiveTime()+" 即将开播");
                        layout_live_container_oitem_txt_state.setTextColor(this.getResources().getColor(R.color.color_gold));
                    } else if(lives.get(0).getLiveStatus() == 10 || lives.get(0).getLiveStatus() == 15){
                        layout_live_container_oitem_txt_state_img.setVisibility(View.VISIBLE);
                        layout_live_container_oitem_txt_state_img.setBackgroundResource(R.drawable.live_icon_end);
                        layout_live_container_oitem_txt_state.setText("直播结束");
                        layout_live_container_oitem_txt_state.setTextColor(this.getResources().getColor(R.color.text_color_gray));
                    } else if(lives.get(0).getLiveStatus() == 30){
                        layout_live_container_oitem_txt_state_img.setVisibility(View.VISIBLE);
                        layout_live_container_oitem_txt_state_img.setBackgroundResource(R.drawable.home_icon_middle);
                        layout_live_container_oitem_txt_state.setText("直播中");
                        layout_live_container_oitem_txt_state.setTextColor(this.getResources().getColor(R.color.color_gold));
                    }
                    if(lives.get(1).getLiveStatus() == 0 ||lives.get(1).getLiveStatus()== 20){
                        layout_live_container_titem_txt_state_img.setVisibility(View.GONE);
                        layout_live_container_titem_txt_state.setText(lives.get(1).getLiveTime()+" 即将开播");
                        layout_live_container_titem_txt_state.setTextColor(this.getResources().getColor(R.color.color_gold));
                    } else if(lives.get(1).getLiveStatus() == 10 || lives.get(1).getLiveStatus() == 15){
                        layout_live_container_titem_txt_state_img.setVisibility(View.VISIBLE);
                        layout_live_container_titem_txt_state_img.setBackgroundResource(R.drawable.live_icon_end);
                        layout_live_container_titem_txt_state.setText("直播结束");
                        layout_live_container_titem_txt_state.setTextColor(this.getResources().getColor(R.color.text_color_gray));
                    } else if(lives.get(1).getLiveStatus() == 30){
                        layout_live_container_titem_txt_state_img.setVisibility(View.VISIBLE);
                        layout_live_container_titem_txt_state_img.setBackgroundResource(R.drawable.home_icon_middle);
                        layout_live_container_titem_txt_state.setText("直播中");
                        layout_live_container_titem_txt_state.setTextColor(this.getResources().getColor(R.color.color_gold));
                    }
                }
            }
        }
    }

    @OnClick({R.id.id_quotation_layout, R.id.id_text_view_economic_calendar, R.id.id_text_view_guide,
            R.id.id_text_view_quick_account, R.id.id_text_view_more,R.id.id_text_view_video_more,
            R.id.id_text_view_live_more,R.id.layout_live_oitem,R.id.layout_live_titem,
            R.id.layout_video_container_oitem_img_back,R.id.layout_video_container_titem_img_back})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_text_view_economic_calendar:
                actionBrowserPage(ApiConfig.ECONOMIC_CALENDAR_URL);
                break;
            case R.id.id_quotation_layout:
                FragmentActivity activity = getActivity();
                if (activity != null && activity instanceof TDMainActivity) {
                    ((TDMainActivity) activity).showQuotationPage();
                }
                break;
            case R.id.id_text_view_guide:
                actionBrowserPage(ApiConfig.NOVICE_GUIDE_URL);
                break;
            case R.id.id_text_view_quick_account:
                actionBrowserPage(ApiConfig.QUICK_ACCOUNT_URL);
                break;
            case R.id.id_text_view_more:
                actionArticlePage();
                break;

            case R.id.layout_video_container_oitem_img_back:
                videoTo(0);
                break;
            case R.id.layout_video_container_titem_img_back:
                videoTo(1);
                break;
            case R.id.layout_live_oitem:
                liveTo(0);
                break;
            case R.id.layout_live_titem:
                liveTo(1);
                break;
            case R.id.id_text_view_live_more:
                Intent dintent = new Intent(this.getActivity(), PullListActivity.class);
                dintent.putExtra("adapter","com.goldplusgold.tradedelay.app.home.live.adapter.LiveListAdapter");
                dintent.putExtra("title",this.getResources().getString(R.string.live_seeding));
                this.getActivity().startActivity(dintent);
                break;
            case R.id.id_text_view_video_more:
                Intent vintent = new Intent(this.getActivity(), PullListActivity.class);
                vintent.putExtra("adapter","com.goldplusgold.tradedelay.app.home.live.adapter.VideoListAdatper");
                vintent.putExtra("title",this.getResources().getString(R.string.video_area));
                vintent.putExtra("isUp",true);
                this.getActivity().startActivity(vintent);
                break;

        }
    }

    private void videoTo(int position) {
        if(videos == null|| videos.getVideos() == null || videos.getVideos().size() == 0){
            return;
        }
        if(position >= videos.getVideos().size() ){
            return;
        }
        Intent intent = new Intent(this.getActivity(), LiveDetailActivity.class);
        intent.putExtra("liveID",videos.getVideos().get(position).getVideoID());
        intent.putExtra("type", LiveDetailActivity.LiveDetailType.VIDEO);
        getActivity().startActivity(intent);
    }

    private void liveTo(int position){
        if (lives == null || lives.getLives() == null || lives.getLives().size() == 0) {
            return;
        }
        if(position >= lives.getLives().size() ){
            return;
        }
        Intent intent = new Intent(this.getActivity(), LiveDetailActivity.class);
        intent.putExtra("liveID",lives.getLives().get(position).getLiveID());
        intent.putExtra("roomID",lives.getLives().get(position).getRoomID());
        if(lives.getLives().get(position).getLiveType() == 0){
            intent.putExtra("type", LiveDetailActivity.LiveDetailType.TEXT_LIVE);
        } else{
            intent.putExtra("type", LiveDetailActivity.LiveDetailType.LIVE);
        }
        getActivity().startActivity(intent);

    }


    private void actionBrowserPage(String url) {
        Intent intent = new Intent(getActivity(), WebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", "财经日历");
        startActivity(intent);
    }

    private void actionArticlePage() {
        Intent intent = new Intent(getActivity(), ExpertArticleActivity.class);
        startActivity(intent);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;
        }

        return true;
    }

    private void requestLiveAndVideoData(){
        Call mLiveCall = LVDataManager.getInstance().getLives(0,2,new LiveBaseCallBack<ResultLives>(getActivity()) {
            @Override
            public void onResponse(Call<ResultLives> call, Response<ResultLives> response) {
                super.onResponse(call, response);
                Logger.i("getLives","success");
                refreshLiveItem(response.body());
            }

            @Override
            public void onFailure(Call<ResultLives> call, Throwable t) {
                super.onFailure(call, t);
                Logger.e("getLives","erro"+t.getMessage());
            }

        });

        Call mVideoCall = LVDataManager.getInstance().getVideos(0,2,new LiveBaseCallBack<ResultVideos>(getContext()) {

            @Override
            public void onResponse(Call<ResultVideos> call, Response<ResultVideos> response) {
                super.onResponse(call, response);
                Logger.i("getVideos","success");
                refreshVideoItem(response.body());
            }

            @Override
            public void onFailure(Call<ResultVideos> call, Throwable t) {
                super.onFailure(call, t);
                Logger.e("getVideos","erro"+t.getMessage());
            }

        });
        addCall(mLiveCall);
        addCall(mVideoCall);
    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        new LoadArticleAsyncTask().execute(AsyncTask.TYPE_NET);
        requestLiveAndVideoData();
    }


    public class LoadBannerAsyncTask extends AsyncTask<Void, Void, List<Banner>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected List<Banner> doInBackground(Void... params) {

            try {
                BannerList bannerModel = HomeService.getInstance().getBannerList();
                if (bannerModel != null) {
                    return bannerModel.getBannerList();
                }
            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<Banner> bannerList) {
            super.onPostExecute(bannerList);
            if (!isAvailableActivity()) {
                return;
            }
            dismisLoadingControl();
            if (bannerList == null || bannerList.isEmpty()) {
                return;
            }

            ArrayList<ImageView> imageList = new ArrayList<>();
            imageList.add(ViewFactory.getImageView(getActivity(), bannerList.get(bannerList.size() - 1).getImgUrl()));


            for (int i = 0; i < bannerList.size(); i++) {
               /* ImageView imageView = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.view_banner, null);
                String imageUrl = bannerList.get(i).getImgUrl();
                Glide.with(getActivity()).load(imageUrl).into(imageView);
                imageList.add(imageView);*/
                imageList.add(ViewFactory.getImageView(getActivity(), bannerList.get(i).getImgUrl()));
            }
            imageList.add(ViewFactory.getImageView(getActivity(), bannerList.get(0).getImgUrl()));
            //设置循环，在调用setData方法前调用
            mBannerViewPager.setCycle(true);
            // 在加载数据前设置是否循环
            mBannerViewPager.setData(imageList, bannerList, mAdCycleViewListener);
            // 设置轮播

            mBannerViewPager.setWheel(true);

            // 设置轮播时间，默认5000ms
            mBannerViewPager.setTime(3000);
            // 设置圆点指示图标组居中显示，默认靠右
            mBannerViewPager.setIndicatorCenter();

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSltpNotificationEventBus(SltpNotificationMessageEvent event) {
        Market.SltpNotification sltpNotification = event.getSltpNotification();
        if (sltpNotification != null && TextUtils.equals(sltpNotification.getType(), "0")) {
            if (sltpNotification.getTriggerData() == null) {
                return;
            }
            Market.SltpRecord sltpRecord = sltpNotification.getTriggerData();
            WarmTipDialog warmTipDialog = new WarmTipDialog();
            warmTipDialog.setSltpRecord(sltpRecord);
            warmTipDialog.show(getChildFragmentManager(), warmTipDialog.getClass().getSimpleName());
        }

        if (sltpNotification != null && TextUtils.equals(sltpNotification.getType(), "1")) {
            List<Market.SltpRecord> deleteData = sltpNotification.getDeleteDataList();
            if (deleteData == null || deleteData.isEmpty()) {
                return;
            }

            Market.SltpRecord record = deleteData.get(0);
            DeleteWarmTipDialog dialog = DeleteWarmTipDialog.newInstance(record.getProdCode(), record.getBearbullType());
            dialog.show(getChildFragmentManager(), DeleteWarmTipDialog.class.getSimpleName());
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQuoteDynaEventBus(DynaMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEDYNA) {
            fillMarketData(event.getIdentification(), event.getQuoteDyna());
        }
    }

    //填充行情数据
    private void fillMarketData(Market.Identification identification, Market.QuoteDyna quoteDyna) {
        if (identification.getInstType() == Market.InstType.AU_TD) {
            setMarketItem(mAUPrice, mAURise, quoteDyna);
        } else if (identification.getInstType() == Market.InstType.AG_TD) {
            setMarketItem(mAGPrice, mAGRose, quoteDyna);
        } else if (identification.getInstType() == Market.InstType.MAU_TD) {
            setMarketItem(mMAUPrice, mMAURise, quoteDyna);
        }
    }


    private void setMarketItem(TextView price, TextView rise, Market.QuoteDyna quoteDyna) {
        price.setText(quoteDyna.getLastPrice());
        rise.setText(quoteDyna.getUpDown() + "  " + quoteDyna.getUpDownRate());
        setTextColor(price, rise, quoteDyna.getLastPrice(), quoteDyna.getLastSettle(), quoteDyna.getUpDownRate());
    }

    private void setTextColor(TextView price, TextView rose, String lastPrice, String lastSettle, String upDownRate) {
        if (StringConvertNumber.parseDouble(lastSettle) > StringConvertNumber.parseDouble(lastPrice)) {
            price.setTextColor(getActivity().getResources().getColor(R.color.color_price_down));
        } else if (StringConvertNumber.parseDouble(lastSettle) == StringConvertNumber.parseDouble(lastPrice)) {
            price.setTextColor(getActivity().getResources().getColor(R.color.td_color_gray_two));
        } else {
            price.setTextColor(getActivity().getResources().getColor(R.color.shallow_red));
        }
        if ("+".equals(upDownRate.substring(0, 1))) {
            rose.setTextColor(getResources().getColor(R.color.shallow_red));
        } else if ("-".equals(upDownRate.substring(0, 1))) {
            rose.setTextColor(getResources().getColor(R.color.color_price_down));
        } else {
            rose.setTextColor(getResources().getColor(R.color.td_color_gray_two));
        }
    }

    private void requestMarket() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                UserInfo userInfo = MyService.getInstance().getmUserInfo();
                String userName = "";
                if (userInfo != null) {
                    userName = userInfo.getUserName();
                }
                Market.Identification.Builder builder = Market.Identification.newBuilder();
                builder.setCategory(Market.Category.ALLINSTQUOTE);
                if (!TextUtils.isEmpty(userName)) {
                    builder.setGoldExpertNo(userName);
                }
                Market.Identification identification = builder.build();
                Market.Response request = Market.Response
                        .newBuilder()
                        .setIdentification(identification).build();
                ChannelManager.sendMessage(0, request, 100175);

            }
        }, 10);
    }

    public class LoadArticleAsyncTask extends AsyncTask<Void, Void, List<Article>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected List<Article> doInBackground(Void... params) {

            try {
                ArticleList articleList = HomeService.getInstance().getArticleList(0, 2, "0");
                if (articleList != null) {
                    return articleList.getArticleList();
                }
            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(List<Article> articleList) {
            super.onPostExecute(articleList);
            if (!isAvailableActivity()) {
                return;
            }
            dismisLoadingControl();
            mScrollView.onRefreshComplete();
            if (articleList == null || articleList.isEmpty()) {
                return;
            }
            mArticleListAdapter.setArrayList(new ArrayList(articleList));
        }
    }


    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);

    }


}


